﻿namespace TradePublish.SysThread.Grasp
{
    using log4net;
    using TradePublish.Common;
    using TradePublish.Service;
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Threading;
    using TradePublish.Dao;
    using TradePublish.Entity;

    public class ClientTaskSubThread
    {
        private Thread doThread;
        public int id;
        public bool isRunning;
        private ILog log = null;
        public List<TradePublishVo> tradePublishs = new List<TradePublishVo>();

        public ClientTaskSubThread()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        public void start()
        {
            this.isRunning = false;
            this.doThread = new Thread(new ThreadStart(this.threadWork));
            this.doThread.IsBackground = true;
            this.doThread.Start();
        }

        private void threadWork()
        {
            GraspTMManager graspTMManager = new GraspTMManager();
            TradePublishManager tradePublishManager = new TradePublishManager();
            ApplyUserContractManager applyUserContractManager = new ApplyUserContractManager();
            while (true)
            {
                if (!isRunning || tradePublishs == null)
                {
                    log.Info("ClientTaskSubThread-" + this.id + "无任务!");
                    Thread.Sleep(10000);//没任务休息10秒
                    continue;
                }
                for (int j = 0; j < tradePublishs.Count; j++)
                {
                    try
                    {
                        #region //1. 采集详情
                        if (!tradePublishs[j].hasGrasped)
                        {
                            while (true)
                            {
                                String[] details = null;
                                bool gifOcrSuccess = true;
                                try
                                {
                                    #region  ///detial[]细节
                                    /// detail[0] 国际分类号;
                                    /// detail[1] 申请日期;
                                    /// detail[2] 申请人名称_中文;
                                    /// detail[3] 申请人地址_中文;
                                    /// detail[4] 申请人名称_英文;
                                    /// detail[5] 申请人地址_英文;
                                    /// detail[6] 使用商品IP;
                                    /// detail[7] 初审公告期号;
                                    /// detail[8] 初审公告日期;
                                    /// detail[9 注册公告期号;
                                    /// detail[10 注册公告日期;
                                    /// detail[11 专用权期限;
                                    /// detail[12 代理人名称;
                                    /// detail[13 是否共有商标;
                                    /// detail[14 商标类型;
                                    /// detail[15 商标流程IP;
                                    /// detail[16] 备注; 
                                    /// detail[17] 注册号  -----
                                    /// detail[18] 商标名称（全部）  -----
                                    /// detail[19] 申请人2       -----
                                    /// detail[20] 申请人3       -----
                                    /// detail[21] 使用商品       -----
                                    /// detail[22] 商标流程       -----
                                    #endregion
                                    log.Info("ClientTaskSubThread-" + this.id + " 开始采集注册号=" + tradePublishs[j].regNo + "的商标...");
                                    details = graspTMManager.doGraspTMInfo(tradePublishs[j].regNo, false);//若内部异常会抛出
                                    if (details == null)
                                    {
                                        //识别的注册号有问题。
                                        log.Info("!!!!!!!!!!ClientTaskSubThread-" + this.id + " 注册号=" + tradePublishs[j].regNo + "的商标信息为null");
                                        gifOcrSuccess = false;
                                    }
                                    else
                                    {
                                        if (tradePublishs[j].category == 0)
                                        {
                                            #region 验证 第一类是否ocr识别正确
                                            if (details[7] == null || details[7].Trim().Equals(""))
                                            {
                                                //识别的注册号有问题。
                                                log.Info("!!!!!!!!!!ClientTaskSubThread-" + this.id + " 注册号=" + tradePublishs[j].regNo + "的商标公告期号为空.");
                                                gifOcrSuccess = false;
                                            }
                                            else if (Convert.ToInt32(details[7]) != tradePublishs[j].issue)
                                            {
                                                //识别的注册号有问题。
                                                log.Info("!!!!!!!!!!ClientTaskSubThread-" + this.id + " 注册号=" + tradePublishs[j].regNo + "的商标[其公告期：" + details[7] + "]不是本期" + tradePublishs[j].issue);
                                                gifOcrSuccess = false;
                                            }
                                            #endregion
                                        }
                                        else if (tradePublishs[j].category == 4)
                                        {
                                            //不验证其是否识别成功。一般识别的都是失败的。\
                                            continue;
                                        }
                                        else
                                        {
                                            #region 验证第二类是否ocr识别正确
                                            //根据状态来查询
                                            DissentStatusSearchTMManager dt = new DissentStatusSearchTMManager();
                                            dt.IntCls = Convert.ToInt32(details[0]);
                                            dt.regNo = tradePublishs[j].regNo;
                                            if (!dt.isMatched(tradePublishs[j].category, (details[7] == null || details[7].Trim().Equals("")) ? 0 : Convert.ToInt32(details[7])))
                                            {
                                                String msgC = "";
                                                if (tradePublishs[j].category == 1)
                                                {
                                                    msgC = "商标注册公告判断错误。";
                                                }
                                                else if (tradePublishs[j].category == 2)
                                                {
                                                    msgC = "商标转让公告判断错误。";
                                                }
                                                else if (tradePublishs[j].category == 3)
                                                {
                                                    msgC = "变更许可人/被许可人名义公告判断错误。";
                                                }
                                                else if (tradePublishs[j].category == 5)
                                                {
                                                    msgC = "注册商标注销公告判断错误。";
                                                }
                                                else if (tradePublishs[j].category == 6)
                                                {
                                                    msgC = "商标异议公告判断错误。";
                                                }
                                                else if (tradePublishs[j].category == 7)
                                                {
                                                    msgC = "未续展商标注销公告判断错误。";
                                                }
                                                log.Error("！！！！！！！注册号" + tradePublishs[j].regNo + "错误" + msgC + "。(trade_publish_id=" + tradePublishs[j].id + ")");
                                                gifOcrSuccess = false;
                                            }
                                            #endregion
                                        } 
                                    }
                                }
                                catch (Exception e)
                                {
                                    log.Error("ClientTaskSubThread-" + this.id + " 采集注册号=" + tradePublishs[j].regNo + "的商标发生异常.", e);
                                    Thread.Sleep(10000);//休息
                                    continue;
                                }
                                if (details != null)
                                {
                                    #region 最终！将已经查找到的注册号详情存入商标数据库,发生异常始终重试
                                    BrandInfoManager brandInfoManager = new BrandInfoManager();
                                    while (true)
                                    {
                                        try
                                        {
                                            brandInfoManager.saveBrandInfo(details);
                                            log.Info("成功将注册号=" + tradePublishs[j].regNo + "的商标入库BRAND_INFO.");
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            //数据库报错
                                            log.Error("将注册号=" + tradePublishs[j].regNo + "的商标入库BRAND_INFO失败.", ex);
                                            Thread.Sleep(5000);//休息 
                                        }
                                    }
                                    #endregion

                                    #region 最终！将已经查找到的注册号详情存入公告数据库,发生异常始终重试
                                    while (true)
                                    {
                                        try
                                        {
                                            tradePublishManager.updateTradePublish(tradePublishs[j].id, details, gifOcrSuccess);
                                            log.Info("GraspRegNoThread-" + this.id + " 成功将注册号=" + tradePublishs[j].regNo + "的商标入库TRADE_PUBLISH.");
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            //数据库报错
                                            log.Error("GraspRegNoThread-" + this.id + " 将注册号=" + tradePublishs[j].regNo + "的商标入库TRADE_PUBLISH失败.", ex);
                                            Thread.Sleep(5000);//休息 
                                        }
                                    }
                                    #endregion

                                    tradePublishs[j].classNo = Convert.ToInt32(details[0] == null ? "0" : details[0]);
                                    tradePublishs[j].tradeName = details[18].ToString();
                                    tradePublishs[j].applyUserName = details[2].ToString();
                                    tradePublishs[j].applyUserAddress = details[3].ToString();
                                    tradePublishs[j].proxyUserName = details[12].ToString();
                                } 
                                else {
                                    tradePublishManager.deleteById(tradePublishs[j].id);
                                    tradePublishs[j].hasAntiSearch = true;
                                    tradePublishs[j].hasStatusSearch = true;
                                }
                                break;
                            }
                            tradePublishs[j].hasGrasped = true;
                        }
                        #endregion

                        #region //2.对第一类商标，进行反查 ，内部异常自己处理
                        if (!tradePublishs[j].hasAntiSearch && tradePublishs[j].category == 0)
                        {
                            while (true)
                            {
                                //（1）拆分商标文字
                                List<TradeNameSplit> tradeNames = null;
                                try
                                {
                                    tradeNames = Utils.splitTradeName(tradePublishs[j].tradeName);
                                }
                                catch (Exception ex)
                                {
                                    log.Error(id + "-执行反查，拆分商标名称[" + tradePublishs[j].regNo + "  " + tradePublishs[j].tradeName + "]异常", ex);
                                    break;
                                }
                                //过滤掉单汉字
                                if (tradeNames != null)
                                {
                                    for (int tr = 0; tr < tradeNames.Count; tr++)
                                    {
                                        if (tradeNames[tr].type == 2 && (tradeNames[tr].key == null || tradeNames[tr].key.Length < 2))
                                        {
                                            tradeNames.RemoveAt(tr);
                                            tr--;
                                        }
                                    }

                                }


                                if (tradeNames == null || tradeNames.Count == 0)
                                {
                                    //不需要反查，修改数据库该记录为已反查
                                    tradePublishManager.setHasAntiSearch(tradePublishs[j].id, 0);//设置为已反查，内部异常自己处理
                                }
                                else
                                {
                                    //对每个拆分后的商标进行反查。日志自己记录，异常自己处理，并不保存数据库
                                    AntiSearchTMManager antiSearchTMManager = new AntiSearchTMManager();
                                    antiSearchTMManager.tradePublishId = tradePublishs[j].id;
                                    antiSearchTMManager.tradeNames = tradeNames;//待反查的商标名（已拆分）
                                    antiSearchTMManager.classNo = tradePublishs[j].classNo;//国际分类号
                                    antiSearchTMManager.regNo = tradePublishs[j].regNo;//待查商标的注册号，用来排除自身用的
                                    antiSearchTMManager.applyUserNameZh = tradePublishs[j].applyUserName;
                                    List<AntiSearchResult> results = null;
                                    List<String[]> details = new List<string[]>();
                                    while (true)
                                    {
                                        try
                                        {
                                            results = antiSearchTMManager.antiSearch(details);
                                            break;
                                        }
                                        catch (Exception e)
                                        {
                                            log.Error(id + "反查发生了异常.", e);
                                            Thread.Sleep(1000);
                                        }
                                    } 
                                    log.Info(id + "将反查结果保存到数据库 DISSENT_TRADE 和 BRAND_INFO");
                                    //将反查结果放入 DISSENT_TRADE 表,（所采集商标详情放入BRAND_INFO） ，日志自己记录，内部异常自己处理。
                                    int saveCount = tradePublishManager.saveAntiSearchResult(results, details, tradePublishs[j].classNo, tradePublishs[j].issue);

                                    //修改数据库该记录为已反查
                                    tradePublishManager.setHasAntiSearch(tradePublishs[j].id, saveCount);//设置为已反查，内部异常自己处理
                                }
                                break;
                            }
                            tradePublishs[j].hasAntiSearch = true;
                        }
                        #endregion

                        #region //3.对第一类商标异议状态查询
                        if (!tradePublishs[j].hasStatusSearch && tradePublishs[j].category == 0)
                        {
                            DissentStatusSerchDao dissentStatusSerchDao = new DissentStatusSerchDao();
                            DissentStatusSearchTMManager dissentStatusSearchTMManager = new DissentStatusSearchTMManager();
                            dissentStatusSearchTMManager.IntCls = tradePublishs[j].classNo;
                            dissentStatusSearchTMManager.regNo = tradePublishs[j].regNo;//待查商标的注册号，用来排除自身用的
                            Boolean matched = dissentStatusSearchTMManager.isMatched();//内部异常自己处理
                            if (matched)
                            {
                                log.Info(id + "-异议状态查询[" + tradePublishs[j].regNo + "]匹配到.");
                                dissentStatusSerchDao.saveStatusSearchResult(tradePublishs[j].id);//内部异常自己处理
                            }
                            else
                            {
                                log.Info(id + "-异议状态查询[" + tradePublishs[j].regNo + "]未匹配到.");
                            }
                            tradePublishManager.setHasStatusSearch(tradePublishs[j].id);//设置为已反查，内部异常自己处理
                        }
                        tradePublishs[j].hasStatusSearch = true;
                        #endregion
                    }
                    catch (Exception exp)
                    {
                        log.Error("！&&&&&&！终于抓到这个异常了，重新处理该商标：", exp);
                        j--;
                        Thread.Sleep(1000);
                    }
                }
                tradePublishs = null;
                isRunning = false;
                log.Info("GraspRegNoThread-" + this.id + "本次任务执行完毕!");

            }
        }
    }
}

